package com.open.demo.apm

import android.os.Build
import android.os.Looper
import android.os.MessageQueue
import android.os.SystemClock
import com.open.demo.joor.Reflect

/**
 *
 */
class ApmLooperMonitor : MessageQueue.IdleHandler {

    var lastCheckPrinterTime:Long = 0
    override fun queueIdle(): Boolean {
        if (SystemClock.uptimeMillis() - lastCheckPrinterTime >= CHECK_TIME) {
            lastCheckPrinterTime = SystemClock.uptimeMillis()
        }
        return false
    }

    companion object {
        private const val CHECK_TIME = 60 * 1000L
    }

    /**
     * Looper.getMainLooper()
     */
    constructor(looper: Looper) {
        addIdleHandler(looper)
    }

    fun addIdleHandler(looper: Looper) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            looper.queue.addIdleHandler(this)
        } else {
            try {
                val queue = Reflect.on(looper).field("mQueue").get<MessageQueue>();
                queue.addIdleHandler(this)
            } catch (e:Exception) {
                e.printStackTrace()
            }
        }
    }

    fun removeIdleHandler(looper: Looper) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            looper.queue.removeIdleHandler(this)
        } else {
            try {
                val queue = Reflect.on(looper).field("mQueue").get<MessageQueue>();
                queue.removeIdleHandler(this)
            } catch (e:Exception) {
                e.printStackTrace()
            }
        }
    }

}